<?php
namespace app\shop\controller;

use app\common\controller\Shop;
use app\common\model\Live\Live as LiveLive;
use app\common\model\Product\Relation;
use think\Request;
use Exception;
use think\Db;
use think\exception\ValidateException;
use think\exception\PDOException;

use app\common\model\Business\Address;
use app\common\model\Business\Commission;
use app\common\model\Business\Record;
use app\common\model\Coupon\Coupon;
use app\common\model\Coupon\Receive;
use app\common\model\Live\Product as LiveProduct;
use app\common\model\Order\Order;
use app\common\model\Order\Product as OrderProduct;
use app\common\model\Pay;
use app\common\model\Product\Product;
use fast\Random;

class Live extends Shop
{
    protected $model = null;
    protected $liveProductModel = null;
    protected $relationModel = null;
    public function __construct(Request $request)
    {
        $this->noLogin = ['index'];
        parent::__construct($request);
        $this->model = new LiveLive();
        $this->liveProductModel = new LiveProduct();
        $this->relationModel = new Relation();
    }
    public function index()
    {
        $count = $this->model->count();
        $live = $this->model->limit(random_int(0,$count),1)->find();
        if(!$live)$this->error('暂无直播');
        $liveProduct = $this->liveProductModel->where(['liveid'=>$live['id'],'type'=>'product'])->select();
        $this->success($live['url'],null,$liveProduct);
    }
    public function product()
    {
        if(!$this->request->isGet())$this->error('请求错误');
        $id = $this->request->get('id',0,'trim');
        $nums = $this->request->get('nums',1,'trim');
        $attrs = $this->request->get('attrs','','trim');
        $liveProduct = $this->liveProductModel->get($id);
        if(!$liveProduct)$this->error('购买出错');
        $propPriceList = $this->relationModel->where('id','in',json_decode($attrs))->column('value,price');
        $price = $liveProduct['price'];
        foreach($propPriceList as $propPrice)
        {
            $price += $propPrice;
        }
        $propList = array_keys($propPriceList);
        if(empty($propList))$this->error('购买出错');
        $list = [];
        $list[] = [
            'product'=>$liveProduct['relation_object'],
            'price'=>$price,
            'attrs'=>$attrs,
            'nums'=>$nums,
            'prop_list'=>$propList,
            'total'=>$price*$nums
        ];
        return $list;
    }
    private function build_cart($id,$nums,$attrs)
    {
        $liveProduct = $this->liveProductModel->get($id);
        if(!$liveProduct)return [];
        $propPriceList = $this->relationModel->where('id','in',json_decode($attrs))->column('value,price');
        $price = $liveProduct['price'];
        foreach($propPriceList as $propPrice)
        {
            $price += $propPrice;
        }
        $propList = array_keys($propPriceList);
        if(empty($propList))return[];
        $list = [];
        $list[] = [
            'id'=>$id,
            'product'=>$liveProduct['relation_object'],
            'price'=>$price,
            'attrs'=>$attrs,
            'nums'=>$nums,
            'prop_list'=>$propList,
            'total'=>$price*$nums,
            'busid'=>$this->business['id'],
            'proid'=>$liveProduct['relation_object']['id']
        ];
        return $list;
    }
    public function order()
    {
        if($this->request->isPost())
        {
            $busid = $this->business['id'];
            $addressModel = new Address();
            $receiveModel = new Receive();
            $orderModel = new Order();
            $payModel = new Pay();
            $where = ['busid'=>$busid];
            //地址
            $businessaddrid = $this->request->post('businessaddrid');
            $address = $addressModel->where($where)->where('id',$businessaddrid)->find();
            if(!$address)$this->error('地址不存在');
            //优惠券
            $couponid = $this->request->post('couponid',0);
            $rate = 1;
            $receive = null;
            if($couponid!=0){
                $where_receive = ['cid'=>$couponid,'receive.status'=>'1','coupon.status'=>'1'];
                $receive = $receiveModel->with(['coupon'])->where($where)->where($where_receive)->find();
                if(!$receive)$this->error('优惠券不存在');
                $rate = $receive->coupon['rate'];
            }
            //订单金额
            $id = $this->request->post('id',0,'trim');
            $nums = $this->request->post('nums',1,'trim');
            $attrs = $this->request->post('attrs','','trim');
            $liveProduct = $this->liveProductModel->get($id);
            if(!$liveProduct)$this->error('购买出错');
            $propPriceList = $this->relationModel->where('id','in',json_decode($attrs))->column('value,price');
            $price = $liveProduct['price'];
            foreach($propPriceList as $propPrice)
            {
                $price += $propPrice;
            }
            $amount = round($price*$nums*$rate,2);
            //支付方式
            $type = $this->request->post('pay','money','trim');
            //订单留言
            $remark = $this->request->post('remark','','trim');
            //订单号
            $code = 'SP'.date('YmdHis',time()).random_int(1000000,9999999);
            
            $result = null;
            $orderStatus = '0';
            $order = null;
            $pay = null;
            Db::startTrans();
            try {
                if($type=='money')
                {
                    //business减余额
                    if($this->business['money']<$amount)throw new Exception('余额不足');
                    $this->business['money'] -= $amount;
                    $this->business->isUpdate()->save();
                    $orderStatus = '1';
                }
                //order添加订单
                $params = [
                    'code'=>$code,
                    'busid'=>$busid,
                    'businessaddrid'=>$businessaddrid,
                    'amount'=>$amount,
                    'remark'=>$remark,
                    'status'=>$orderStatus,
                    'pay'=>$type
                ];
                if($receive){
                    $params['couponid'] = $couponid;
                }
                $order = $orderModel->allowField(true)->create($params);
                if($orderStatus=='1')
                {
                    $cart = $this->build_cart($id,$nums,$attrs);
                    $this->payed($order,$cart,$receive);
                }
                $payList = $orderModel->getPaycodeList();
                if($type!='money'){
                    $params = [
                        'code'=>$code,
                        'name'=>'商品购买',
                        'third'=>json_encode(['busid'=>$this->business['id']]),
                        'type'=>$type,
                        'total'=>$amount,
                        'price'=>$amount,
                        'cashier'=>'1',
                        'status'=>$orderStatus,
                    ];
                    $params['qrcode'] = $payList[$type];
                    $pay = $payModel->create($params);
                }
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if (false === $result) {
                $this->error('下单失败');
            }
            if($orderStatus=='1')
            {
                $this->success('下单成功');
            }else{
                $this->result($pay['id'],-1,"未支付");
            }
        }
    }
    private function payed($order,$cart,$receive=null)
    {
        $commissionModel = new Commission();
        $recordModel = new Record();
        $productModel = new Product();
        $orderProductModel = new OrderProduct();
        $receiveModel = new Receive();

        //coupon修改优惠券状态
        $rate = 1;
        if(isset($order['couponid'])&&$order['couponid']){
            if(!$receive){
                $where_receive = ['cid'=>$order['couponid'],'receive.status'=>'1','coupon.status'=>'1'];
                $receive = $receiveModel->with(['coupon'])->where('busid',$this->business['id'])->where($where_receive)->find();
            }
            $rate = $receive['rate'];
            $receive['status'] = '0';
            $receive->allowField(true)->isUpdate(true)->save();
        }

        //orderProduct添加订单商品
        $params = [];
        foreach($cart as $c)
        {
            $params[] = [
                'orderid'=>$order['id'],
                'busid'=>$this->business['id'],
                'proid'=>$c['proid'],
                'pronum'=>$c['nums'],
                'price'=>$c['price']*$rate,
                'total'=>$c['total']*$rate,
                'attrs'=>$c['attrs'],
                'status'=>'0',
                'code'=>'SP'.date('YmdHis',time()).Random::numeric(7),
            ];
        }
        $result = $orderProductModel->isUpdate(false)->saveAll($params);
        
        
        //product减库存
        foreach($cart as $c)
        {
            $product = $productModel->get($c['proid']);
            $product['stock'] -= $c['nums'];
            if($product['stock']<0)throw new Exception('库存不足');
            $result = $productModel->isUpdate()->save();
        }

        if($this->business['parentid']){
            //commission添加佣金
            $params = [
                'orderid'=>$order['id'],
                'busid'=>$this->business['id'],
                'parentid'=>$this->business['parentid'],
                'amount'=>$order['amount']*config('site.amountRate'),
                'type'=>'product',
                'status'=>'0',
            ];
            $commissionModel->allowField(true)->save($params);
        }

        //record添加消费记录
        foreach($cart as $c)
        {
            $params = [
                'total'=>-$c['total']*$rate,
                'content'=>'购买直播商品：【'.$c['product']['name'].'】'.join('|',$c['prop_list']).'花费了 ￥'.$c['total']*$rate.' 元',
                'busid'=>$this->business['id']
            ];
        }
        $recordModel->allowField(true)->save($params);

        //live_product减直播商品库存
        foreach($cart as $c)
        {
            $liveProduct = $this->liveProductModel->get($c['id']);
            $liveProduct['stock'] -= $c['nums'];
            if($liveProduct['stock']<0)throw new Exception('库存不足');
            $liveProduct->isUpdate()->save();
        }
    }
    public function pay()
    {
        $orderModel = new Order();
        $busid = $this->business['id'];
        $payid = $this->request->param('payid');
        $pay = Pay::where(['id'=>$payid])->find();
        if(!$pay||(json_decode($pay['third'])->busid!=$busid))$this->error('订单不存在');
        if($this->request->isPut())
        {
            $money = $this->request->post('money');
            if($money==$pay['price'])
            {
                $result = null;
                Db::startTrans();
                try {
                    //pay 修改已支付
                    $pay['status'] = '1';
                    $pay->isUpdate()->save();
                    //order
                    $order = $orderModel->where('code',$pay['code'])->find();
                    $order['status'] = '1';
                    $result = $order->isUpdate()->save();
                    $id = $this->request->post('id',0,'trim');
                    $nums = $this->request->post('nums',1,'trim');
                    $attrs = $this->request->post('attrs','','trim');
                    $liveProduct = $this->liveProductModel->get($id);
                    if(!$liveProduct)throw new Exception('购买出错');
                    $cart = $this->build_cart($id,$nums,$attrs);
                    $this->payed($order,$cart);
                    Db::commit();
                } catch (ValidateException|PDOException|Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if (false === $result) {
                    $this->error('下单失败');
                }
                $this->success('支付成功');
            }else{
                $this->result(null,-1,'支付失败');
            }
        }
    }
}
